package com.echat.api.demo.util;

import com.echat.api.demo.info.bizdata.EncryptedBizData;
import com.echat.api.demo.info.User;
import com.echat.api.demo.wechat.aes.AesException;
import com.echat.api.demo.wechat.aes.WXBizMsgCrypt;

/**
 * Created by EChat
 * echat API接口工具类
 */
public class EChatAPIUtil {
    private static WXBizMsgCrypt wxBizMsgCrypt = null;

    static {
        try {
            wxBizMsgCrypt = new WXBizMsgCrypt(EChatAPIConfig.token, EChatAPIConfig.encodingAesKey, EChatAPIConfig.appId);
        } catch (AesException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param user
     * @return 根据会员信息返回提交给一洽的metaData参数值, 获取后使用如下：
     * 1.加载chat.js的时候将metaData接入一洽
     * _echat.('initParam',{metaData:metaData});
     * 2.手动打开对话窗口是将metaData接入一洽(参数追加，其他参数要保留）
     * chat.html?metaData=${metaData}
     */
    public static String getUserMetaData(User user) throws Exception {
        if (user == null || StringUtil.isEmpty(user.getUid())) {
            return null;
        }
        //1.将user对象转成xml字符串
        String metaDataXml = XMLUtil.toXML(user);
        System.out.println(metaDataXml);
        //2.将xml进行加密
        String encryptMetaData = wxBizMsgCrypt.encrypt(metaDataXml);
        return  encryptMetaData;
    }

    /**
     * @param metaData 一洽传递给客户的业务系统参数中的加密会员信息
     *                注意：metaData是原加密字符串 不是utf8编码encode过的结果
     * @return 返回会员信息的user对象
     */
    public static User getUserFromMetaData(String metaData)throws Exception {
        if (StringUtil.isEmpty(metaData)) {
            return null;
        }
        //1.将加密的metaData信息解密成xml字符串
        String metaDataXml = wxBizMsgCrypt.decrypt(metaData);
        System.out.println(metaDataXml);
        //2.将xml转换成user对象
        return (User) XMLUtil.toBean(metaDataXml, User.class);
    }

    /**
     * @param bizData
     * @return 将一洽post给客户业务系统的加密数据进行解密
     */
    public static String decryptPostBizData(String bizData) throws Exception{
        if (StringUtil.isEmpty(bizData)) {
            return null;
        }
        EncryptedBizData encryptedBizData = (EncryptedBizData) XMLUtil.toBean(bizData,EncryptedBizData.class);

        return wxBizMsgCrypt.decrypt(encryptedBizData.getEncrypt());
    }

    /**
     * @param nonce 随机数
     * @param timestamp 时间戳
     * @param signature 签名
     * @return 验证成功 返回 true 验证失败返回false
     * 如果要使用指定的RUL来实时接收一洽的业务数据，需要通过一洽get请求的校验，
     * 一洽才能正常向业务数据接收的URL post业务数据
     */
    public static boolean verifyURL(String nonce, String timestamp, String signature)throws Exception {
        return wxBizMsgCrypt.verifyUrl(signature, timestamp, nonce);
    }

    public static void main(String[] strings) throws Exception {
//        System.out.println(wxBizMsgCrypt.encrypt("<xml>\n" +
//                "<uid>1-22</uid>\n" +
//                "<name>秦江利</name>\n" +
//                "<nickName>qinjiangli</nickName>\n" +
//                "<email>276202460@qq.com</email>\n" +
//                "<photo>http://file.echatsoft.com/group1/M00/24/5D/wKhCBFhSTh-AfOvpAAANhXD2Biw812.png</photo>\n" +
//                "</xml>"));
//        System.out.println(wxBizMsgCrypt.decrypt("YrU6kXHIBgy03Vq9QbJU54cwPSxyJlgeJJV8/xCDlsFPONdHhoJzINJqVI5Wo6yVJMjaOaf5Xt1Wup3UQo5/lDnRM3y5hnxGcI82f7aQ0wRcm4HQVvHmwqP+9+lnBbLL"));
//        System.out.println(wxBizMsgCrypt.encrypt("usermetaData"));
//
//        System.out.println(wxBizMsgCrypt.decrypt("FWWhFhBp9nbMc5gbR8scmZJcgidAAHkuGqU61KIWJanxl/XRBd8CXUTx0P92AQYNGk4RbVMcVRc8c2IGNUoDjNIGGuIREyD9XOipYI2J569rciG75hjfq/Hcbj1abCUYpbUneOkSxhNIWZVieE/UYUdKVz4U+2TlWk1h1/tm2hSaOguiavZ0/Jq+NxInM461PhJrpwJDL5+tvZbvEGTljt/tTR5yqyU8Fzlvbik6GuhVFRgWiEsR5WxtQORoKNkO2L5qVkJ2yGvIN2WOH2PAgkjPds9Pafk2Gq9FLMlLEaM0RCYntJoUOtIvy+gqa9hMQZawrEnkYTL6CSOzgl7qMofP7K348cLDrjx2hTxY0mbNkQkRLfew+xjajMZul89VkRSe3DlO1Uab3BoSr0FZDBOjj/y9kXzyLtxAnDx/qsKq350c+yPdjNC+E5bptxs+N7uLVpQYlWMNTwYjUgah6rO5KQDCToYt45eEVTDlm6hlfmcYoPnMa9Xii/s0fxnNk5w4lsBAD2YyWqOvaozwzecDKiKiC3cy4TuDyfmdaK0EmD1nIdK7cMrrR3aNFv6AGjaKepm4jKuEwjpyj8EOwicTSuIH0PLpZJE1bdJOGOykJVJX5v0dcH5sv562P094cOnobJegcJKK9PGbxBi2A38Go3xEYzG/BIzIrOuOaehQlkfOhdk+bwWMpJxind0LJEoic2YlmayC0aUZch2pzQ=="));
//        System.out.println(URLUtil.encode("FWWhFhBp9nbMc5gbR8scmZJcgidAAHkuGqU61KIWJanxl/XRBd8CXUTx0P92AQYNGk4RbVMcVRc8c2IGNUoDjNIGGuIREyD9XOipYI2J569rciG75hjfq/Hcbj1abCUYpbUneOkSxhNIWZVieE/UYUdKVz4U+2TlWk1h1/tm2hSaOguiavZ0/Jq+NxInM461PhJrpwJDL5+tvZbvEGTljt/tTR5yqyU8Fzlvbik6GuhVFRgWiEsR5WxtQORoKNkO2L5qVkJ2yGvIN2WOH2PAgkjPds9Pafk2Gq9FLMlLEaM0RCYntJoUOtIvy+gqa9hMQZawrEnkYTL6CSOzgl7qMofP7K348cLDrjx2hTxY0mbNkQkRLfew+xjajMZul89VkRSe3DlO1Uab3BoSr0FZDBOjj/y9kXzyLtxAnDx/qsKq350c+yPdjNC+E5bptxs+N7uLVpQYlWMNTwYjUgah6rO5KQDCToYt45eEVTDlm6hlfmcYoPnMa9Xii/s0fxnNk5w4lsBAD2YyWqOvaozwzecDKiKiC3cy4TuDyfmdaK0EmD1nIdK7cMrrR3aNFv6AGjaKepm4jKuEwjpyj8EOwicTSuIH0PLpZJE1bdJOGOykJVJX5v0dcH5sv562P094cOnobJegcJKK9PGbxBi2A38Go3xEYzG/BIzIrOuOaehQlkfOhdk+bwWMpJxind0LJEoic2YlmayC0aUZch2pzQ=="));
        User user = new User();
        user.setUid("0017");
        user.setName("一洽Younger");
        user.setPhoto("http://file.echatsoft.com/group1/M00/24/5D/wKhCBFhSTh-AfOvpAAANhXD2Biw812.png");
        user.setAge(18);
        user.setBirthday("1988-01-01");
        user.setGender(2);
        user.setMaritalStatus(1);
        user.setEmail("3512248949@qq.com");
        user.setGrade(9);
        user.setCategory("金牌会员");
        String metaData = getUserMetaData(user);
        System.out.println(metaData);
        System.out.println(URLUtil.encode(metaData));
//        metaData = "+R78Ca5d6IPIfqvFVaL46xjCq1gTPoT9uIR3ZBRMURrpqwx68L7sUYRtRtCraGoul+4CHbXEVXQ+am74FjYKmkHbUpSbPcXtlVltXar702m7vASwbsya0M8rRVO2Q8VT";
//        metaData = URLUtil.encode(metaData);
//        System.out.println(metaData);
//        User user1= getUserFromMetaData(URLUtil.decode(metaData));
//        System.out.println(user1.getName());
//        System.out.println(user1.getUid());
//        System.out.println(user1.getPhoto());
//        System.out.println(user1.getName());
//        System.out.println(user1.getAge());
//        System.out.println(user1.getGender());
//        System.out.println(user1.getMaritalStatus());

    }
}
